import {Injectable} from "@angular/core";
import {DOMAIN_SERVER_URL} from "../constants";
import {Observable} from "rxjs";
import {HttpClient} from "@angular/common/http";
import {RestResult} from "../entity/rest-result";

@Injectable()
export class FileService {
  constructor (
    private http: HttpClient
  ){ }

    handlerFileUpload(filesToUpload: Array<File>): Promise<any> {
        return this.makeFileRequest(DOMAIN_SERVER_URL, "imageFiles", filesToUpload);
    }

    handlerImageUpload(filesToUpload: File, checkItemId: number): Observable<RestResult<string>> {
      return this.uploadFile(DOMAIN_SERVER_URL + checkItemId, "file", filesToUpload);
    }

    makeFileRequest(url: string, fileName: string, files: Array<File>): Promise<any> {
        return new Promise((resolve, reject) => {
            const formData: any = new FormData();
            const xhr = new XMLHttpRequest();
            for (let i = 0; i < files.length; i++) {
                formData.append(fileName, files[i], files[i].name);
            }
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        resolve(JSON.parse(xhr.response));
                    } else {
                        reject(xhr.response);
                    }
                }
            };
            xhr.open("POST", url, true);
            xhr.send(formData);
        });
    }

    makeSingleFileRequest(url: string, fileName: string, file: File): Promise<any> {
      return new Promise((resolve, reject) => {
        const formData: any = new FormData();
        const xhr = new XMLHttpRequest();
        formData.append(fileName, file, file.name);
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4) {
            if (xhr.status === 200) {
              resolve(JSON.parse(xhr.response));
            } else {
              reject(xhr.response);
            }
          }
        };
        xhr.open("POST", url, true);
        xhr.send(formData);
      });
    }

    uploadFile(url: string, fileName: string, file: File): Observable<RestResult<string>> {
      const formData: any = new FormData();
      formData.append(fileName, file, file.name);
      return this.http.post<RestResult<string>>(url , formData);
    }

    uploadSingleFile(file: File): Observable<RestResult<string>> {
      const formData: any = new FormData();
      formData.append('file', file, file.name);
      return this.http.post<RestResult<string>>(DOMAIN_SERVER_URL + "/windbell/upload/1" , formData);
    }

    handlerFileDownload(fileName: string) {
        // window.open(this._fileDownloadUrl + "/" + fileName);
    }

}
